﻿using Dapper;
using DapperExtensions.Sql;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Reflection;

namespace BJoin.DapperExtension.Postgresql
{
    public class PostgresqlImplement : DapperExtensions.DapperImplementor
    {
        public PostgresqlImplement(ISqlGenerator sqlGenerator) : base(sqlGenerator)
        {
        }
        protected override DynamicParameters ToDynamicParameter<T>(Dictionary<string, object> parameters)
        {
            DynamicParameters dynamicParameters = new DynamicParameters();
            foreach (var parameter in parameters)
            {
                if (IsTheType(typeof(T),parameter,"json"))
                    dynamicParameters.Add(parameter.Key, new JsonParameter(parameter.Value));
                else if (parameter.Value is Array)
                    dynamicParameters.Add(parameter.Key, new ArrayParameter(parameter.Value));
                else
                    dynamicParameters.Add(parameter.Key, parameter.Value);
            }
            return dynamicParameters;
        }
        protected override void AppendDynamicParameter<T>(DynamicParameters dynamicParameters, IEnumerable<KeyValuePair<string, object>> keyValues)
        {
            foreach (var keyValue in keyValues)
            {
                if (IsTheType(typeof(T), keyValue, "json"))
                    dynamicParameters.Add(keyValue.Key, new JsonParameter(IgnoreNull(keyValue.Value)));
                else if (keyValue.Value is Array)
                    dynamicParameters.Add(keyValue.Key, new ArrayParameter(keyValue.Value));
                else
                    dynamicParameters.Add(keyValue.Key, keyValue.Value);
            }
        }
    }
}
